package com.coolweather.android;

import static com.coolweather.android.contants.Constants.AQI_URL;
import static com.coolweather.android.contants.Constants.FORECAST_URL;
import static com.coolweather.android.contants.Constants.KEY;
import static com.coolweather.android.contants.Constants.NOWWEATHER_URL;
import static com.coolweather.android.contants.Constants.PIC_URL;
import static com.coolweather.android.contants.Constants.SUGGEST_URL;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.LayoutDirection;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.coolweather.android.databinding.ActivityWeatherBinding;
import com.coolweather.android.databinding.ForecastItemBinding;
import com.coolweather.android.gson.AQI;
import com.coolweather.android.gson.BingPic;
import com.coolweather.android.gson.Forecast;
import com.coolweather.android.gson.NowWeather;
import com.coolweather.android.gson.Suggest;
import com.coolweather.android.util.HttpUtil;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
ActivityWeatherBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }


        binding=ActivityWeatherBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.includeTitle.titleCity.setOnClickListener(v->{
            binding.drawerLayout.openDrawer(GravityCompat.START);
        });


            Intent intent=getIntent();
//            intent.putExtra("spot",spot);
//            intent.putExtra("location",location);
            String spot=intent.getStringExtra("spot");
        String location=intent.getStringExtra("location");
        Log.d("test2","onCreate:"+spot+":"+location);

        showTitle(spot);
        requestWeather(location);
        loadBingPic();
    }

    private void loadBingPic() {
        HttpUtil.sendOkHttpRequest(PIC_URL, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(()->{
                    Toast.makeText(WeatherActivity.this, "访问每日一图失败", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String strJson=response.body().string();
                Log.d("test","onResponse:"+strJson);

                BingPic bingPic=gson.fromJson(strJson,BingPic.class);
                if(bingPic!=null&&bingPic.getCode()==200){
                    runOnUiThread(()->{
                        Glide.with(WeatherActivity.this).load(bingPic.getData().getUrl()).into(binding.bingPicImg);
                    });
                }
            }
        });

    }

    private void requestWeather(String location) {

        String url0=NOWWEATHER_URL+"?"+"location="+location+"&key="+KEY;
        String url1=FORECAST_URL+"?"+"location="+location+"&key="+KEY;
        String url2=AQI_URL+"?"+"location="+location+"&key="+KEY;
        String url3=SUGGEST_URL+"?"+"location="+location+"&key="+KEY+"&type=1,3,8";

        Gson gson=new Gson();

        Observable<Response> observable0=HttpUtil.request(url0);
        Observable<Response> observable1=HttpUtil.request(url1);
        Observable<Response> observable2=HttpUtil.request(url2);
        Observable<Response> observable3=HttpUtil.request(url3);
        Observable.zip(
                observable0,
                observable1,
                observable2,
                observable3,
                (response0, response1, response2, response3) ->{
                    try {
                        NowWeather nowWeather=gson.fromJson(response0.body().string(),NowWeather.class);
                        Forecast forecast=gson.fromJson(response1.body().string(),Forecast.class);
                        AQI aqi=gson.fromJson(response2.body().string(),AQI.class);
                        Suggest suggest=gson.fromJson(response3.body().string(),Suggest.class);



                        return new Object[]{nowWeather,forecast,aqi,suggest};
                    }

                    finally {

                        response1.close();
                        response2.close();
                        response3.close();
                        response0.close();
                    }
                }
        ).observeOn(AndroidSchedulers.mainThread()).
                subscribe(
                        results->{
                            showNowWeather((NowWeather) results[0]);
                            showForecast((Forecast) results[1]);
                            showAQI((AQI)results[2]);
                            showSuggest((Suggest) results[3]);
                        },
                        throwable -> {
                            Toast.makeText(this, "访问网络操作出错1", Toast.LENGTH_SHORT).show();
                        }
                );

    }

    private void showForecast(Forecast forecast) {
        if(forecast!=null&&forecast.getCode().equals("200")){
            binding.includeForecast.forecastLayout.removeAllViews();
            for(Forecast.DailyDTO dailyDTO : forecast.getDaily()){
                View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,
                        binding.includeForecast.forecastLayout,false);
                TextView dateText=(TextView)view.findViewById(R.id.date_text);
                TextView infoText=(TextView)view.findViewById(R.id.info_text);
                TextView maxText=(TextView)view.findViewById(R.id.max_text);
                TextView minText=(TextView)view.findViewById(R.id.min_text);
                dateText.setText(dailyDTO.getFxDate());
                infoText.setText(dailyDTO.getTextDay());
                maxText.setText(dailyDTO.getTempMax());
                minText.setText(dailyDTO.getTempMin());

                binding.includeForecast.forecastLayout.addView(view);
            }
        }else {
            Toast.makeText(this, "访问网络操作出错2", Toast.LENGTH_SHORT).show();
        }

    }

    private void showSuggest(Suggest suggest) {
        if(suggest!=null&&suggest.getCode().equals("200")){
            binding.includeSuggestion.comfortText.setText(String.format("舒适度指数,\n%s\n%s",
                    suggest.getDaily().get(2).getCategory(),
                    suggest.getDaily().get(2).getText()
                    ));
            binding.includeSuggestion.sportText.setText(String.format("运动指数,\n%s\n%s",
                    suggest.getDaily().get(0).getCategory(),
                    suggest.getDaily().get(0).getText()
            ));
            binding.includeSuggestion.wearText.setText(String.format("穿衣指数,\n%s\n%s",
                    suggest.getDaily().get(1).getCategory(),
                    suggest.getDaily().get(1).getText()
            ));
        }else{
            Toast.makeText(this, "获取天气指数出错3", Toast.LENGTH_SHORT).show();
        }



    }

    private void showAQI(AQI aqi) {
        if(aqi!=null&&aqi.getCode().equals("200")){
            binding.includeAqi.aqiText.setText(aqi.getNow().getAqi());
            binding.includeAqi.pm25Text.setText(aqi.getNow().getPm2p5());
        }else{
            Toast.makeText(this, "获取天气指数出错4", Toast.LENGTH_SHORT).show();
        }

    }

    private void showNowWeather(NowWeather nowWeather) {
        if(nowWeather!=null&&nowWeather.getCode().equals("200")){
            String temp=nowWeather.getNow().getTemp();
            binding.includeNow.degreeText.setText(String.format("%s℃",temp));
            binding.includeNow.weatherInfoText.setText(nowWeather.getNow().getText());
        }

    }
    Gson gson=new Gson();

    private void showTitle(String spot) {
        binding.includeTitle.titleCity.setText(spot);
        SimpleDateFormat fromat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        binding.includeTitle.titleUpdateTime.setText(fromat.format(new Date()));
    }

}